package com.example.demofile.controller;

import com.example.demofile.common.AjaxResult;
import com.example.demofile.common.Constants;
import com.example.demofile.utils.StringUtil;
import com.example.demofile.utils.file.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
 
@RestController
@RequestMapping()
public class FileController {
    
    @Value("${file.path}")
    private String file_path;
    
    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/common/upload")
    public AjaxResult fileUpload(MultipartFile file) throws Exception {

        if (file == null) {
            // TODO
            return AjaxResult.error("文件上传失败");
        }
        // 文件实际存放路径
        String filePath = file_path;

        if (file.isEmpty()) {
            return AjaxResult.error("文件上传失败");
        }
        // 获取上传时的文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件大小，单位：b
        long fileSize = file.getSize();

        // 获取文件后缀名 .XX
        int suffixIndex = originalFilename.lastIndexOf(".");
        String fileSuffix = originalFilename.substring(suffixIndex);
        // TODO 新文件名
        String newFileName = StringUtil.uuid() + fileSuffix;
        String url = Constants.FILE_BASE_URL + newFileName;
        // 生成网络访问地址
        // String fileUrl = file_path + newFileName;
        // 生成新文件路径
        File dest = new File(filePath + newFileName);
        try {
            file.transferTo(dest);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("filename", originalFilename);
            ajax.put("url", url);
            return ajax;
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = file_path + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtil.setAttachmentResponseHeader(response, realFileName);
            FileUtil.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e)
        {
            System.out.println("下载文件失败");
        }
    }
}